package com.meida.module.arc.provider.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.mybatis.query.CriteriaUpdate;
import com.meida.common.utils.ApiAssert;
import com.meida.module.arc.client.entity.ArcDb;
import com.meida.module.arc.provider.mapper.ArcDbMapper;
import com.meida.module.arc.provider.service.ArcDbRecordService;
import com.meida.module.arc.provider.service.ArcDbService;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.mybatis.model.ResultBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.meida.common.base.entity.EntityMap;
import com.meida.common.mybatis.query.CriteriaQuery;
import org.springframework.transaction.annotation.Propagation;
import com.meida.common.mybatis.query.CriteriaSave;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 数据库备份配置接口实现类
 *
 * @author flyme
 * @date 2021-12-25
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ArcDbServiceImpl extends BaseServiceImpl<ArcDbMapper, ArcDb> implements ArcDbService {

    @Autowired
    private ArcDbRecordService arcDbRecordService;

    @Override
    public ResultBody beforeAdd(CriteriaSave cs, ArcDb t, EntityMap extra) {
        ApiAssert.isNotEmpty("配置内容不能为空",t);
        ApiAssert.isNotEmpty("是否自动不能为空",t.getAuto());
        if(1==t.getAuto()){
            ApiAssert.isNotEmpty("自动备份时间不能为空",t.getAutoTime());
        }
        //删除已有配置
        QueryWrapper<ArcDb> deleteWrapper = new QueryWrapper<>();
        this.remove(deleteWrapper);
        t.setPath(this.arcDbRecordService.getDefaultRecordPath());
        return ResultBody.ok();
    }



    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<ArcDb> cq, ArcDb db, EntityMap requestMap) {
      cq.orderByDesc("db.createTime");
      return ResultBody.ok();
    }



    @Override
    public ResultBody getSetting(Map var1) {
        //获取默认配置
        QueryWrapper<ArcDb> dbQuery = new QueryWrapper<>();
        dbQuery.orderByDesc("createTime");
        List<ArcDb> list = this.list(dbQuery);
        ArcDb db = new ArcDb();
        if(FlymeUtils.isNotEmpty(list)){
            db = list.get(0);
            //如果存在多个  则删除其他的
            if(list.size()>1){
                for(int i=1;i<list.size();i++){
                    this.removeById(list.get(i).getDbId());
                }
            }
        }else{
            db.setAuto(0);
            db.setPath(arcDbRecordService.getDefaultRecordPath());
            db.setType(0);
            this.save(db);
        }
        return ResultBody.ok(db);
    }
}
